package org.shj.book2.chapter06.improve;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public abstract class AbstractData {

	protected final char[] buffer;
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
	private ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
	private ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
	
	public AbstractData(int size){		
		this.buffer = new char[size];
		for(int i = 0 ; i < size; i++){
			buffer[i] = '*';
		}
	}
	
	public char[] read() throws InterruptedException{
		readLock.lock();
		try{
			return doRead();			
		}finally{
			readLock.unlock();
		}
	}
	
	public void write(char c) throws InterruptedException{
		writeLock.lock();
		try{
			doWrite(c);
		}finally{
			writeLock.unlock();
		}
	}
	
	protected abstract char[] doRead();
	
	protected abstract void doWrite(char c);
	
	
}
